package quq.missq.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import quq.missq.Constants;
import quq.missq.MLog;
import quq.missq.MissQApplication;
import quq.missq.activity.LoginActivity;


public class VolleyTool{

    private static MissQApplication getApplication(){
        return MissQApplication.getInstance();
    }

    public static RequestQueue getRequestQueue(){
        return getApplication().getRequestQueue();
    }

    public static ImageLoader getImageLoader(){
        return getApplication().getImageLoader();
    }


    public static <T> void post(Activity activity,String url,final Map<String, String> params,final HTTPListener httpListener,int requestCode,Class<T> t)
    {
        doRequest(activity,Request.Method.POST, url, params, httpListener,requestCode,t);
    }

    public static <T> void get(Activity activity,String url,final Map<String, String> params,final HTTPListener httpListener,int requestCode,Class<T> t)
    {
        StringBuilder sb = new StringBuilder(url);
        if(params != null){
            sb.append('?');
            for(Map.Entry<String, String> entry : params.entrySet()){
                try {
                    sb.append(entry.getKey()).append('=')
                            .append(URLEncoder.encode(entry.getValue(), Constants.CODE_TYPE)).append('&');
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            sb.deleteCharAt(sb.length()-1);
        }
       // System.out.println("get请求url"+sb.toString());
        MLog.e(sb.toString());
        doRequest(activity,Request.Method.GET, sb.toString(), null, httpListener,requestCode,t);
    }
    //测试
    public static <T> void get1(Activity activity,String url,final Map<String, String> params,final HTTPListener httpListener,int requestCode,Class<T> t)
    {
        StringBuilder sb = new StringBuilder(url);
        if(params != null){
            sb.append('?');
            for(Map.Entry<String, String> entry : params.entrySet()){
                try {
                    sb.append(entry.getKey()).append('=')
                            .append(URLEncoder.encode(entry.getValue(), Constants.CODE_TYPE)).append('&');
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            sb.deleteCharAt(sb.length()-1);
        }
       // System.out.println("get请求url"+sb.toString());
        doRequest1(activity, Request.Method.GET, sb.toString(), null, httpListener, requestCode, t);
    }
    private static <T> void doRequest1(final Activity context,final int type,String url,final Map<String, String> params,final HTTPListener httpListener,final int requestCode,final Class<T> t){
        StringRequest postRequest = new StringRequest(
                type,
                url,
                new Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //System.out.println("请求返回数据"+response);
                       // Log.e("WelcomeActivity", response);
                        try {
                            if(t != null){
                                Gson gson = new Gson();
                                T bean = gson.fromJson(response, t);
                                if(httpListener != null){
                                    httpListener.onResponse(bean,requestCode);}
                            }else{
                                if(httpListener != null){
                                    httpListener.onResponse(response, requestCode);}
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Context context = getApplication().getApplicationContext();
                Toast.makeText(context, VolleyErrorHelper.getMessage(error, context),Toast.LENGTH_LONG).show();
                if(httpListener != null){
                    httpListener.onErrorResponse(error,requestCode);}
            }
        }) {
            @Override
            protected Map<String, String> getParams()
                    throws AuthFailureError {
                return params;
            }
        };
        getApplication().addToRequestQueue(postRequest);
    }
    private static <T> void doRequest(final Activity context,final int type,String url,final Map<String, String> params,final HTTPListener httpListener,final int requestCode,final Class<T> t){
        StringRequest postRequest = new StringRequest(
                type,
                url,
                new Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //System.out.println("请求返回数据"+response);
                        MLog.e(response);
                        try {
                            JSONObject obj = new JSONObject(response);
                            int code = obj.getInt("code");
                            String message = obj.getString("message");
                            if(code < 0 && requestCode == Constants.LOGIN){
                                if(code == -202){
                                    Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                                }else if(code == -203){
                                    Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                                }
                            }else if(code == -100){
                                Toast.makeText(context, "你的账号在其他设备登录，请重新登录",Toast.LENGTH_LONG).show();
                                Intent intent = new Intent();
                                intent.setClass(context,LoginActivity.class);
                                context.startActivity(intent);
                                context.finish();
                            }else if(code == -302){
                                Toast.makeText(context, message,Toast.LENGTH_LONG).show();
                                context.finish();
                            }else if(code == -304){
                                Toast.makeText(context, message,Toast.LENGTH_LONG).show();
                                context.finish();
                            }else{
                                if(t != null){
                                    Gson gson = new Gson();
                                    T bean = gson.fromJson(response, t);
                                    if(httpListener != null){
                                        httpListener.onResponse(bean,requestCode);}
                                }else{
                                    if(httpListener != null){
                                        httpListener.onResponse(response, requestCode);}
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Context context = getApplication().getApplicationContext();
                Toast.makeText(context, VolleyErrorHelper.getMessage(error, context),Toast.LENGTH_LONG).show();
                if(httpListener != null){
                    httpListener.onErrorResponse(error,requestCode);}
            }
        }) {
            @Override
            protected Map<String, String> getParams()
                    throws AuthFailureError {
                return params;
            }
        };
        getApplication().addToRequestQueue(postRequest);
    }

    public interface HTTPListener{
        <T> void onResponse(T t, int requestCode);
        void onErrorResponse(VolleyError error, int requestCode);
    }
}
